<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;

/**
 * 订单售后单
 */
class orderaftersaleModel extends Model
{
    use \app\traits\orderaftersalescope;

    // 表名,不含前缀
    protected $table = 'order_aftersale';

    protected function serializeDate($date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected $appends = [
        'type_text',
        'aftersale_status_text',
        'aftersale_status_desc',
        'refund_status_text',
        'btns',
    ];

    // 发货状态
    const DISPATCH_STATUS_NOSEND = 0;       // 未发货
    const DISPATCH_STATUS_SENDED = 1;       // 已发货
    const DISPATCH_STATUS_GETED = 2;        // 已收货

    // 售后状态
    const AFTERSALE_STATUS_CANCEL = -2;       // 售后取消
    const AFTERSALE_STATUS_REFUSE = -1;       // 拒绝
    const AFTERSALE_STATUS_NOOPER = 0;       // 未处理
    const AFTERSALE_STATUS_AFTERING = 1;       // 处理中
    const AFTERSALE_STATUS_AGREE = 2;          // 同意售后完成
    const AFTERSALE_STATUS_OK = 3;          // 售后完成


    // 退款状态
    const REFUND_STATUS_REFUSE = -1;       // 拒绝退款(不用了)
    const REFUND_STATUS_NOREFUND = 0;       // 未退款
    const REFUND_STATUS_FINISH = 1;       // 同意

    public static function getSn($user_id)
    {
        $rand     = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return 'A' . $order_sn . $id;
    }


    // 获取售后列表
    public static function getList($params)
    {
        $user = \app\service\auth::getUser();
        $type = $params['type'] ?? 'all';
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $offset = ($page - 1) * $per_page;

        $aftersale = (new self())->where('member_id', $user->id);

        if ($type != 'all') {
            $aftersale = $aftersale->{$type}();
        }

        $total = $aftersale->count();
        $data = $aftersale->orderBy('id', 'desc')->offset($offset)->limit($per_page)->get();

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];

        return $result;
    }


    public static function detail($params)
    {
        $user = \app\service\auth::getUser();
        $id   = $params['id'] ?? 0;

        $aftersale = (new self())->where('member_id', $user->id)->find($id);

        if (!$aftersale) {
            throw new Exception('售后单不存在');
        }

        $aftersale->express = DB::table('order_aftersale_return')->where('order_aftersale_id', $id)->first();

        $aftersale->logs;
        foreach ($aftersale->logs as $log) {
            $aftersale->latest = strip_tags($log->content);
        }

        return $aftersale;
    }


    public static function aftersale($params)
    {
        $orderAftersale = DB::transaction(function () use ($params) {

            $user = \app\service\auth::getUser();

            $type          = $params['type'];
            $order_id      = $params['order_id'];
            $order_item_id = $params['order_item_id'];
            $phone         = $params['phone'];
            $reason        = $params['reason'] ?? '用户申请售后';
            $content       = $params['content'] ?? '';
            $images        = (!empty($params['images']) && is_array($params['images'])) ? $params['images'] : [];

            $order = orderModel::canAftersale()
                ->whereRaw("member_id='{$user->id}' Or customer_id='{$user->id}'")
                ->where('id', $order_id)
                ->lockForUpdate()
                ->first();
            if (!$order) {
                throw new Exception('订单不存在或不可售后');
            }

            $item = orderitemModel::where('id', $order_item_id)
                ->where('order_id', $order_id)
                ->first();
            if (!$item) {
                throw new Exception('参数错误');
            }

            if (!in_array($item->aftersale_status, [
                orderitemModel::AFTERSALE_STATUS_REFUSE,
                orderitemModel::AFTERSALE_STATUS_NOAFTER
            ])) {
                throw new Exception('当前订单商品不可申请售后');
            }

            $orderAftersale                       = new self();
            $orderAftersale->aftersale_sn         = self::getSn($user->id);
            $orderAftersale->member_id            = $user->id;
            $orderAftersale->type                 = $type;
            $orderAftersale->phone                = $phone;
            $orderAftersale->activity_id          = $item['activity_id'];
            $orderAftersale->activity_type        = $item['activity_type'];
            $orderAftersale->order_id             = $order_id;
            $orderAftersale->order_item_id        = $order_item_id;
            $orderAftersale->goods_id             = $item['goods_id'];
            $orderAftersale->goods_sku_price_id   = $item['goods_sku_price_id'];
            $orderAftersale->goods_sku_text       = $item['goods_sku_text'];
            $orderAftersale->goods_title          = $item['goods_title'];
            $orderAftersale->goods_image          = $item['goods_image'];
            $orderAftersale->goods_original_price = $item['goods_original_price'];
            $orderAftersale->discount_fee         = $item['discount_fee'];
            $orderAftersale->goods_price          = $item['goods_price'];
            $orderAftersale->goods_num            = $item['goods_num'];
            $orderAftersale->dispatch_status      = $item['dispatch_status'];
            $orderAftersale->dispatch_fee         = $item['dispatch_fee'];
            $orderAftersale->aftersale_status     = self::AFTERSALE_STATUS_NOOPER;
            $orderAftersale->refund_status        = self::REFUND_STATUS_NOREFUND;      // 未退款
            $orderAftersale->refund_fee           = 0;
            $orderAftersale->save();

            // 增加售后单变动记录、
            orderaftersalelogModel::operAdd($order, $orderAftersale, $user, 'user', [
                'reason'  => '您的售后服务单已申请成功，等待售后处理',
                'content' => "申请原因：$reason <br>相关描述： $content",
                'images'  => $images
            ]);

            $ext                 = $item->ext_arr ?: [];
            $ext['aftersale_id'] = $orderAftersale->id;
            // 修改订单 item 状态，申请售后
            $item->aftersale_status = orderitemModel::AFTERSALE_STATUS_AFTERING;
            // 套餐订单
            if (!empty($item->goods_combo)) {
                $goods_combo = json_decode($item->goods_combo);
                $combo_goods = $goods_combo->goods ?? [];
                foreach ($combo_goods as $combo_goods_key => $combo_goods_item) {
                    $combo_goods_item->aftersale_status = orderitemModel::AFTERSALE_STATUS_AFTERING;
                    $combo_goods[$combo_goods_key] = $combo_goods_item;
                }
                $goods_combo->goods = $combo_goods;
                $item->goods_combo = json_encode($goods_combo);
            }
            $item->ext = json_encode($ext);
            $item->save();
            orderactionModel::operAdd($order, $item, $user, 'user', '用户申请售后');

            return $orderAftersale;
        });

        return $orderAftersale;
    }


    // 取消售后单
    public static function operCancel($params)
    {
        $user = \app\service\auth::getUser();

        $aftersale = self::canCancel()
            ->where('member_id', $user->id)
            ->where('id', $params['id'])
            ->first();

        if (!$aftersale) {
            throw new Exception('售后单不存在或不可取消');
        }

        $order = orderModel::where('member_id', $user->id)->where('id', $aftersale['order_id'])->first();
        if (!$order) {
            throw new Exception('订单不存在');
        }

        $orderitemModel = orderitemModel::where('id', $aftersale['order_item_id'])->first();
        if (
            !$orderitemModel
            || in_array(
                $orderitemModel['refund_status'],
                [orderitemModel::REFUND_STATUS_OK, orderitemModel::REFUND_STATUS_FINISH]
            )
        ) {
            // 不存在， 或者已经退款
            throw new Exception('退款商品不存在或已退款');
        }

        $aftersale = DB::transaction(function () use ($aftersale, $order, $orderitemModel, $user) {
            $aftersale->aftersale_status = self::AFTERSALE_STATUS_CANCEL;        // 取消售后单
            $aftersale->save();

            orderaftersalelogModel::operAdd($order, $aftersale, $user, 'user', [
                'reason'  => '用户取消申请售后',
                'content' => '用户取消申请售后',
                'images'  => []
            ]);

            // 修改订单 item 为未申请售后
            $orderitemModel->aftersale_status = orderitemModel::AFTERSALE_STATUS_NOAFTER;
            $orderitemModel->refund_status    = orderitemModel::REFUND_STATUS_NOREFUND;
            $orderitemModel->save();

            orderactionModel::operAdd($order, $orderitemModel, $user, 'user', '用户取消申请售后');

            return $aftersale;
        });

        return $aftersale;
    }


    // 删除售后单
    public static function operDelete($params)
    {
        $user = \app\service\auth::getUser();

        $aftersale = self::canDelete()->where('member_id', $user->id)->where('id', $params['id'])->first();

        if (!$aftersale) {
            throw new Exception('售后单不存在或不可删除');
        }

        $order     = orderModel::where('id', $aftersale['order_id'])->first();
        $aftersale = DB::transaction(function () use ($aftersale, $order, $user) {
            $copyAftersale = $aftersale->toArray();
            $aftersale->delete();        // 删除售后单

            orderaftersalelogModel::operAdd($order, $copyAftersale, $user, 'user', [
                'reason'  => '用户删除售后单',
                'content' => '用户删除售后单',
                'images'  => []
            ]);

            return $aftersale;
        });

        return $aftersale;
    }


    public function getTypeTextAttribute($value)
    {
        $text = '';
        switch ($this->attributes['type']) {
            case 'refund':
                $text = '退款';
                break;
            case 'return':
                $text = '退货';
                break;
            case 'other':
                $text = '其他';
                break;
        }

        return $text;
    }


    public function getDispatchStatusTextAttribute($value)
    {
        $text = '';
        switch ($this->attributes['dispatch_status']) {
            case self::DISPATCH_STATUS_NOSEND:
                $text = '未发货';
                break;
            case self::DISPATCH_STATUS_SENDED:
                $text = '已发货';
                break;
            case self::DISPATCH_STATUS_GETED:
                $text = '已收货';
                break;
        }

        return $text;
    }


    public function getRefundStatusTextAttribute($value)
    {
        $text = '';
        switch ($this->attributes['refund_status']) {
            case self::REFUND_STATUS_REFUSE:
                $text = '拒绝退款';
                break;
            case self::REFUND_STATUS_NOREFUND:
                $text = '未退款';
                break;
            case self::REFUND_STATUS_FINISH:
                $text = '已退款';
                break;
        }

        return $text;
    }


    public function getAftersaleStatusTextAttribute($value)
    {
        return $this->getStatus('status_text');
    }


    public function getAftersaleStatusDescAttribute($value)
    {
        return $this->getStatus('status_desc');
    }


    public function getBtnsAttribute($value)
    {
        return $this->getStatus('btns');
    }


    public function getStatus($type)
    {
        $text = '';
        $desc = '';
        $btns = [];
        switch ($this->attributes['aftersale_status']) {
            case self::AFTERSALE_STATUS_CANCEL:
                $text = '售后取消';
                $desc = '您取消了售后申请';
                $btns = ['delete'];     // 删除
                break;
            case self::AFTERSALE_STATUS_REFUSE:
                $text = '售后拒绝';
                $desc = '您的申请被拒绝，请点击查看详情';
                $btns = ['delete'];     // 删除
                break;
            case self::AFTERSALE_STATUS_NOOPER:
                $text = '提交申请';
                $desc = '您的服务单已申请成功，等待售后处理';
                $btns = ['cancel'];     // 取消申请
                break;
            case self::AFTERSALE_STATUS_AFTERING:
                $text = '处理中';
                $desc = '您的服务单正在处理中，请耐心等待';
                $btns = ['cancel'];     // 取消申请
                break;
            case self::AFTERSALE_STATUS_OK:
                $text = '售后完成';
                $desc = '服务已完成，感谢您的支持';
                $btns = ['delete'];     // 删除
                break;
        }

        return $type == 'status_text' ? $text : ($type == 'status_desc' ? $desc : $btns);
    }


    public function logs()
    {
        return $this->hasMany(orderaftersalelogModel::class, 'order_aftersale_id', 'id')->orderBy('id', 'desc');
    }

    public function order()
    {
        return $this->belongsTo(orderModel::class, 'order_id', 'id');
    }

    public function item()
    {
        return $this->belongsTo(orderitemModel::class, 'order_item_id', 'id');
    }

    public function member()
    {
        return $this->belongsTo(memberModel::class, 'member_id', 'id');
    }

    public function return()
    {
        return $this->hasOne(orderaftersalereturnModel::class, 'order_aftersale_id', 'id');
    }



}
